#include "SubjectInfoDialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QGroupBox>
#include <QMessageBox>
#include <QTimer>
#include <QScrollArea>
#include <QTabWidget>

SubjectInfoDialog::SubjectInfoDialog(DatabaseManager *dbManager, QWidget *parent)
    : QDialog(parent), m_dbManager(dbManager) {

    setWindowTitle("被试信息采集");
    setMinimumSize(800, 700);

    // 创建文字转语音管理器
    m_ttsManager = new TextToSpeechManager(this);

    // 设置欢迎提示文本
    m_welcomeText = "欢迎您使用脑健康监测系统。\n\n"
                    "我是您的专业心理健康顾问，接下来将为您进行一次全面的心理健康评估。\n\n"
                    "在我们开始之前，请您做好以下准备：\n\n"
                    "请确保您所在的环境安静且没有干扰。\n"
                    "请找一个舒适的位置坐下，保持自然放松的状态。\n"
                    "测试前请避免摄入咖啡因或其他刺激性物质。\n"
                    "建议您将手机调至静音或勿扰模式。\n\n"
                    "现在，我需要您提供一些基本信息和社会学信息。这些信息将帮助我们提供更准确的评估结果。\n\n"
                    "请放心，您提供的所有信息都将严格保密。\n\n"
                    "准备好了吗？让我们一起开始这段心理健康之旅。";

    setupUi();
    connectSignals();

    // 使用定时器延迟播放欢迎信息，确保界面已经显示
    QTimer::singleShot(500, this, &SubjectInfoDialog::playWelcomeMessage);
}

SubjectInfoDialog::~SubjectInfoDialog() {
    // 类成员会自动清理
}

void SubjectInfoDialog::setupUi() {
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 创建选项卡控件
    m_tabWidget = new QTabWidget(this);

    // 创建各选项卡
    QWidget *basicInfoTab = new QWidget(m_tabWidget);
    QWidget *extendedInfoTab = new QWidget(m_tabWidget);
    QWidget *socialInfoTab = new QWidget(m_tabWidget);
    QWidget *healthInfoTab = new QWidget(m_tabWidget);
    QWidget *personalityTab = new QWidget(m_tabWidget);
    QWidget *socialRelationsTab = new QWidget(m_tabWidget);
    QWidget *cultureValuesTab = new QWidget(m_tabWidget);

    // 设置各选项卡的内容
    setupBasicInfoTab(basicInfoTab);
    setupExtendedInfoTab(extendedInfoTab);
    setupSocialInfoTab(socialInfoTab);
    setupHealthInfoTab(healthInfoTab);
    setupPersonalityTab(personalityTab);
    setupSocialRelationsTab(socialRelationsTab);
    setupCultureValuesTab(cultureValuesTab);

    // 添加选项卡
    m_tabWidget->addTab(basicInfoTab, "基本信息");
    m_tabWidget->addTab(extendedInfoTab, "扩展信息");
    m_tabWidget->addTab(socialInfoTab, "社会经济信息");
    m_tabWidget->addTab(healthInfoTab, "健康信息");
    m_tabWidget->addTab(personalityTab, "个人特质");
    m_tabWidget->addTab(socialRelationsTab, "社会关系");
    m_tabWidget->addTab(cultureValuesTab, "文化与价值观");

    // 状态标签
    m_statusLabel = new QLabel("请填写必要信息（带*号的项目）", this);
    m_statusLabel->setAlignment(Qt::AlignCenter);

    // 提交按钮
    m_submitButton = new QPushButton("提交信息并开始测试", this);

    // 添加到主布局
    mainLayout->addWidget(m_tabWidget);
    mainLayout->addWidget(m_statusLabel);
    mainLayout->addWidget(m_submitButton);
}

void SubjectInfoDialog::setupBasicInfoTab(QWidget *tab) {
    QFormLayout *layout = new QFormLayout(tab);

    // 创建控件
    m_nameEdit = new QLineEdit(tab);
    m_genderCombo = new QComboBox(tab);
    m_genderCombo->addItems({"男", "女", "其他"});
    m_ageSpinBox = new QSpinBox(tab);
    m_ageSpinBox->setRange(1, 120);
    m_ageSpinBox->setValue(25);

    // 设置控件样式，与其他选项卡一致
    QString controlStyle = "background-color: white; color: black;";
    m_nameEdit->setStyleSheet(controlStyle);
    m_genderCombo->setStyleSheet(controlStyle);
    m_ageSpinBox->setStyleSheet(controlStyle);

    // 创建标签，确保文本颜色可见
    QLabel *nameLabel = new QLabel("姓名 *:", tab);
    QLabel *genderLabel = new QLabel("性别 *:", tab);
    QLabel *ageLabel = new QLabel("年龄 *:", tab);

    // 设置标签样式，确保文本可见
    QString labelStyle = "color: black;";
    nameLabel->setStyleSheet(labelStyle);
    genderLabel->setStyleSheet(labelStyle);
    ageLabel->setStyleSheet(labelStyle);

    // 添加到布局
    layout->addRow(nameLabel, m_nameEdit);
    layout->addRow(genderLabel, m_genderCombo);
    layout->addRow(ageLabel, m_ageSpinBox);

    // 添加说明文字
    QLabel *noteLabel = new QLabel("注意: 带*号的项目为必填项，其他信息均为选填", tab);
    noteLabel->setStyleSheet("color: blue;");
    layout->addRow("", noteLabel);
}

void SubjectInfoDialog::setupExtendedInfoTab(QWidget *tab) {
    QFormLayout *layout = new QFormLayout(tab);

    // 城乡分布
    m_residenceTypeCombo = new QComboBox(tab);
    m_residenceTypeCombo->addItems({"城市", "城镇", "农村"});

    // 省市信息
    QHBoxLayout *locationLayout = new QHBoxLayout();
    m_provinceEdit = new QLineEdit(tab);
    m_cityEdit = new QLineEdit(tab);
    locationLayout->addWidget(new QLabel("省/自治区:", tab));
    locationLayout->addWidget(m_provinceEdit);
    locationLayout->addWidget(new QLabel("市/县:", tab));
    locationLayout->addWidget(m_cityEdit);

    // 民族/人种
    m_ethnicityEdit = new QLineEdit(tab);

    layout->addRow("居住类型:", m_residenceTypeCombo);
    layout->addRow("所在地区:", locationLayout);
    layout->addRow("民族/人种:", m_ethnicityEdit);
}

void SubjectInfoDialog::setupSocialInfoTab(QWidget *tab) {
    QFormLayout *layout = new QFormLayout(tab);

    m_educationCombo = new QComboBox(tab);
    m_educationCombo->addItems({"小学", "初中", "高中", "大专", "本科", "硕士", "博士", "其他"});
    m_educationCombo->setCurrentIndex(4); // 默认本科

    m_majorEdit = new QLineEdit(tab);

    m_maritalStatusCombo = new QComboBox(tab);
    m_maritalStatusCombo->addItems({"未婚", "已婚", "离异", "丧偶", "其他"});

    m_childrenSpinBox = new QSpinBox(tab);
    m_childrenSpinBox->setRange(0, 10);
    m_childrenSpinBox->setValue(0);

    m_occupationEdit = new QTextEdit(tab);
    m_occupationEdit->setMaximumHeight(60);

    m_incomeCombo = new QComboBox(tab);
    m_incomeCombo->addItems({"5万以下", "5-10万", "10-20万", "20-50万", "50万以上", "不愿透露"});
    m_incomeCombo->setCurrentIndex(2); // 默认10-20万

    m_socialClassCombo = new QComboBox(tab);
    m_socialClassCombo->addItems({"下层", "中下层", "中层", "中上层", "上层", "不愿透露"});
    m_socialClassCombo->setCurrentIndex(2); // 默认中层

    m_familyMembersSpinBox = new QSpinBox(tab);
    m_familyMembersSpinBox->setRange(1, 20);
    m_familyMembersSpinBox->setValue(3);

    layout->addRow("教育程度:", m_educationCombo);
    layout->addRow("专业:", m_majorEdit);
    layout->addRow("婚恋状态:", m_maritalStatusCombo);
    layout->addRow("子女数量:", m_childrenSpinBox);
    layout->addRow("职业情况:", m_occupationEdit);
    layout->addRow("年收入:", m_incomeCombo);
    layout->addRow("社会阶层自我认同:", m_socialClassCombo);
    layout->addRow("家庭成员数量:", m_familyMembersSpinBox);
}

void SubjectInfoDialog::setupHealthInfoTab(QWidget *tab) {
    QVBoxLayout *mainLayout = new QVBoxLayout(tab);

    QFormLayout *healthLayout = new QFormLayout();

    m_medicalHistoryEdit = new QTextEdit(tab);
    m_medicalHistoryEdit->setMaximumHeight(60);

    m_medicationEdit = new QTextEdit(tab);
    m_medicationEdit->setMaximumHeight(60);

    m_sleepInfoEdit = new QTextEdit(tab);
    m_sleepInfoEdit->setMaximumHeight(60);

    m_stressInfoEdit = new QTextEdit(tab);
    m_stressInfoEdit->setMaximumHeight(60);

    // 吸烟选项
    QHBoxLayout *smokerLayout = new QHBoxLayout();
    m_smokerGroup = new QButtonGroup(tab);
    m_smokerYes = new QRadioButton("是", tab);
    m_smokerNo = new QRadioButton("否", tab);
    m_smokerGroup->addButton(m_smokerYes);
    m_smokerGroup->addButton(m_smokerNo);
    m_smokerNo->setChecked(true); // 默认不吸烟
    smokerLayout->addWidget(m_smokerYes);
    smokerLayout->addWidget(m_smokerNo);

    // 饮酒选项
    QHBoxLayout *drinkerLayout = new QHBoxLayout();
    m_drinkerGroup = new QButtonGroup(tab);
    m_drinkerYes = new QRadioButton("是", tab);
    m_drinkerNo = new QRadioButton("否", tab);
    m_drinkerGroup->addButton(m_drinkerYes);
    m_drinkerGroup->addButton(m_drinkerNo);
    m_drinkerNo->setChecked(true); // 默认不饮酒
    drinkerLayout->addWidget(m_drinkerYes);
    drinkerLayout->addWidget(m_drinkerNo);

    // 近视选项
    QHBoxLayout *myopiaLayout = new QHBoxLayout();
    m_myopiaGroup = new QButtonGroup(tab);
    m_myopiaYes = new QRadioButton("是", tab);
    m_myopiaNo = new QRadioButton("否", tab);
    m_myopiaGroup->addButton(m_myopiaYes);
    m_myopiaGroup->addButton(m_myopiaNo);
    m_myopiaNo->setChecked(true); // 默认不近视
    myopiaLayout->addWidget(m_myopiaYes);
    myopiaLayout->addWidget(m_myopiaNo);

    m_sleepHoursSpinBox = new QSpinBox(tab);
    m_sleepHoursSpinBox->setRange(1, 24);
    m_sleepHoursSpinBox->setValue(7);
    m_sleepHoursSpinBox->setSuffix(" 小时");

    m_physicalHealthCombo = new QComboBox(tab);
    m_physicalHealthCombo->addItems({"很差", "较差", "一般", "良好", "优秀"});
    m_physicalHealthCombo->setCurrentIndex(3); // 默认良好

    m_mentalHealthCombo = new QComboBox(tab);
    m_mentalHealthCombo->addItems({"很差", "较差", "一般", "良好", "优秀"});
    m_mentalHealthCombo->setCurrentIndex(3); // 默认良好

    m_exerciseFrequencyCombo = new QComboBox(tab);
    m_exerciseFrequencyCombo->addItems({"从不", "很少（每月1-2次）", "偶尔（每周1-2次）", "经常（每周3-5次）", "每天"});
    m_exerciseFrequencyCombo->setCurrentIndex(3); // 默认经常

    QHBoxLayout *bmiLayout = new QHBoxLayout();
    QLabel *heightLabel = new QLabel("身高(cm):", tab);
    m_heightSpinBox = new QDoubleSpinBox(tab);
    m_heightSpinBox->setRange(50, 250);
    m_heightSpinBox->setValue(170);
    m_heightSpinBox->setSingleStep(0.5);

    QLabel *weightLabel = new QLabel("体重(kg):", tab);
    m_weightSpinBox = new QDoubleSpinBox(tab);
    m_weightSpinBox->setRange(20, 300);
    m_weightSpinBox->setValue(65);
    m_weightSpinBox->setSingleStep(0.5);

    m_bmiLabel = new QLabel("BMI: 22.5", tab);

    bmiLayout->addWidget(heightLabel);
    bmiLayout->addWidget(m_heightSpinBox);
    bmiLayout->addWidget(weightLabel);
    bmiLayout->addWidget(m_weightSpinBox);
    bmiLayout->addWidget(m_bmiLabel);

    healthLayout->addRow("病史:", m_medicalHistoryEdit);
    healthLayout->addRow("当前用药:", m_medicationEdit);
    healthLayout->addRow("睡眠描述:", m_sleepInfoEdit);
    healthLayout->addRow("平均睡眠时长:", m_sleepHoursSpinBox);
    healthLayout->addRow("生活压力:", m_stressInfoEdit);
    healthLayout->addRow("是否吸烟:", smokerLayout);
    healthLayout->addRow("是否饮酒:", drinkerLayout);
    healthLayout->addRow("是否近视:", myopiaLayout);
    healthLayout->addRow("身体健康自评:", m_physicalHealthCombo);
    healthLayout->addRow("心理健康自评:", m_mentalHealthCombo);
    healthLayout->addRow("体育锻炼频率:", m_exerciseFrequencyCombo);
    healthLayout->addRow("身高体重:", bmiLayout);

    mainLayout->addLayout(healthLayout);
}

void SubjectInfoDialog::setupPersonalityTab(QWidget *tab) {
    QFormLayout *layout = new QFormLayout(tab);

    m_mbtiCombo = new QComboBox(tab);
    m_mbtiCombo->addItems({
        "不知道", "INTJ", "INTP", "ENTJ", "ENTP",
        "INFJ", "INFP", "ENFJ", "ENFP",
        "ISTJ", "ISFJ", "ESTJ", "ESFJ",
        "ISTP", "ISFP", "ESTP", "ESFP"
    });

    // 左撇子选项
    QHBoxLayout *leftHandedLayout = new QHBoxLayout();
    m_leftHandedGroup = new QButtonGroup(tab);
    m_leftHandedYes = new QRadioButton("是", tab);
    m_leftHandedNo = new QRadioButton("否", tab);
    m_leftHandedGroup->addButton(m_leftHandedYes);
    m_leftHandedGroup->addButton(m_leftHandedNo);
    m_leftHandedNo->setChecked(true); // 默认不是左撇子
    leftHandedLayout->addWidget(m_leftHandedYes);
    leftHandedLayout->addWidget(m_leftHandedNo);

    m_hobbiesEdit = new QTextEdit(tab);
    m_hobbiesEdit->setMaximumHeight(100);
    m_hobbiesEdit->setPlaceholderText("请输入您的爱好，多个爱好请用逗号分隔");

    layout->addRow("MBTI人格类型:", m_mbtiCombo);
    layout->addRow("是否左撇子:", leftHandedLayout);
    layout->addRow("爱好:", m_hobbiesEdit);
}

void SubjectInfoDialog::setupSocialRelationsTab(QWidget *tab) {
    QFormLayout *layout = new QFormLayout(tab);

    m_socialMediaUsageCombo = new QComboBox(tab);
    m_socialMediaUsageCombo->addItems({
        "从不使用", "很少使用（每周几次）", "偶尔使用（每天不到1小时）",
        "经常使用（每天1-3小时）", "频繁使用（每天3小时以上）"
    });
    m_socialMediaUsageCombo->setCurrentIndex(2); // 默认偶尔使用

    m_socialNetworkSizeSpinBox = new QSpinBox(tab);
    m_socialNetworkSizeSpinBox->setRange(0, 1000);
    m_socialNetworkSizeSpinBox->setValue(20);
    m_socialNetworkSizeSpinBox->setSingleStep(5);

    m_communityInvolvementCombo = new QComboBox(tab);
    m_communityInvolvementCombo->addItems({
        "从不参与", "很少参与", "偶尔参与", "经常参与", "积极参与"
    });
    m_communityInvolvementCombo->setCurrentIndex(2); // 默认偶尔参与

    layout->addRow("社交媒体使用情况:", m_socialMediaUsageCombo);
    layout->addRow("社会支持网络规模\n(亲密朋友数量):", m_socialNetworkSizeSpinBox);
    layout->addRow("社区参与度:", m_communityInvolvementCombo);
}

void SubjectInfoDialog::setupCultureValuesTab(QWidget *tab) {
    QFormLayout *layout = new QFormLayout(tab);

    m_religionCombo = new QComboBox(tab);
    m_religionCombo->addItems({
        "无宗教信仰", "佛教", "道教", "基督教", "天主教", "伊斯兰教", "其他", "不愿透露"
    });

    m_politicalOrientationCombo = new QComboBox(tab);
    m_politicalOrientationCombo->addItems({
        "极左", "偏左", "中立", "偏右", "极右", "不关心政治", "不愿透露"
    });
    m_politicalOrientationCombo->setCurrentIndex(2); // 默认中立

    m_languageUsageCombo = new QComboBox(tab);
    m_languageUsageCombo->addItems({
        "仅使用汉语", "主要使用汉语，略懂外语", "汉语和外语均流利", "主要使用外语", "其他"
    });
    m_languageUsageCombo->setCurrentIndex(1); // 默认主要使用汉语

    m_lifeSatisfactionCombo = new QComboBox(tab);
    m_lifeSatisfactionCombo->addItems({
        "非常不满意", "不太满意", "一般", "比较满意", "非常满意"
    });
    m_lifeSatisfactionCombo->setCurrentIndex(3); // 默认比较满意

    m_socialConcernCombo = new QComboBox(tab);
    m_socialConcernCombo->addItems({
        "完全不关注", "很少关注", "偶尔关注", "经常关注", "密切关注"
    });
    m_socialConcernCombo->setCurrentIndex(2); // 默认偶尔关注

    m_coreValuesCombo = new QComboBox(tab);
    m_coreValuesCombo->addItems({
        "传统保守", "中庸平衡", "开放创新", "不确定"
    });
    m_coreValuesCombo->setCurrentIndex(1); // 默认中庸平衡

    layout->addRow("宗教信仰:", m_religionCombo);
    layout->addRow("政治倾向:", m_politicalOrientationCombo);
    layout->addRow("语言使用情况:", m_languageUsageCombo);
    layout->addRow("生活满意度:", m_lifeSatisfactionCombo);
    layout->addRow("对社会问题的关注度:", m_socialConcernCombo);
    layout->addRow("核心价值观倾向:", m_coreValuesCombo);
}

void SubjectInfoDialog::connectSignals() {
    connect(m_submitButton, &QPushButton::clicked, this, &SubjectInfoDialog::onSubmitButtonClicked);
    connect(m_ttsManager, &TextToSpeechManager::stateChanged, this, &SubjectInfoDialog::onTtsStateChanged);

    // 教育程度变化时更新专业输入框状态
    connect(m_educationCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &SubjectInfoDialog::onEducationLevelChanged);

    // 婚姻状况变化时更新子女数量输入框状态
    connect(m_maritalStatusCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &SubjectInfoDialog::onMaritalStatusChanged);

    // 身高体重变化时更新BMI
    connect(m_heightSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            this, &SubjectInfoDialog::updateBMI);
    connect(m_weightSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            this, &SubjectInfoDialog::updateBMI);

    // 初始化BMI值
    updateBMI();
}

void SubjectInfoDialog::updateBMI() {
    double height = m_heightSpinBox->value() / 100.0; // 转换为米
    double weight = m_weightSpinBox->value();

    if (height > 0) {
        double bmi = weight / (height * height);
        m_bmiLabel->setText(QString("BMI: %1").arg(bmi, 0, 'f', 1));
    }
}

void SubjectInfoDialog::playWelcomeMessage() {
    m_statusLabel->setText("正在播放欢迎信息...");
    m_ttsManager->speak(m_welcomeText);
}

void SubjectInfoDialog::onTtsStateChanged(QTextToSpeech::State state) {
    if (state == QTextToSpeech::Ready) {
        m_statusLabel->setText("欢迎信息播放完毕，请填写必要信息（带*号的项目）");
    }
}

void SubjectInfoDialog::onEducationLevelChanged(int index) {
    // 如果教育程度是小学或初中，禁用专业输入框
    bool enableMajor = (index >= 2); // 高中及以上可以输入专业
    m_majorEdit->setEnabled(enableMajor);
    if (!enableMajor) {
        m_majorEdit->clear();
    }
}

void SubjectInfoDialog::onMaritalStatusChanged(int index) {
    // 如果婚姻状况是未婚，禁用子女数量输入框
    bool enableChildren = (index != 0); // 非未婚可以输入子女数量
    m_childrenSpinBox->setEnabled(enableChildren);
    if (!enableChildren) {
        m_childrenSpinBox->setValue(0);
    }
}

QMap<QString, QString> SubjectInfoDialog::collectOptionalData() {
    QMap<QString, QString> optionalData;

    // 扩展信息
    optionalData["extended:residence_type"] = m_residenceTypeCombo->currentText();
    if (!m_provinceEdit->text().trimmed().isEmpty()) {
        optionalData["extended:province"] = m_provinceEdit->text().trimmed();
    }
    if (!m_cityEdit->text().trimmed().isEmpty()) {
        optionalData["extended:city"] = m_cityEdit->text().trimmed();
    }
    if (!m_ethnicityEdit->text().trimmed().isEmpty()) {
        optionalData["extended:ethnicity"] = m_ethnicityEdit->text().trimmed();
    }

    // 社会学信息
    optionalData["social:education"] = m_educationCombo->currentText();
    if (!m_majorEdit->text().trimmed().isEmpty()) {
        optionalData["social:major"] = m_majorEdit->text().trimmed();
    }
    optionalData["social:marital_status"] = m_maritalStatusCombo->currentText();
    optionalData["social:children"] = QString::number(m_childrenSpinBox->value());
    if (!m_occupationEdit->toPlainText().trimmed().isEmpty()) {
        optionalData["social:occupation"] = m_occupationEdit->toPlainText().trimmed();
    }
    optionalData["social:income"] = m_incomeCombo->currentText();
    optionalData["social:social_class"] = m_socialClassCombo->currentText();
    optionalData["social:family_members"] = QString::number(m_familyMembersSpinBox->value());

    // 健康信息
    if (!m_medicalHistoryEdit->toPlainText().trimmed().isEmpty()) {
        optionalData["health:medical_history"] = m_medicalHistoryEdit->toPlainText().trimmed();
    }
    if (!m_medicationEdit->toPlainText().trimmed().isEmpty()) {
        optionalData["health:medication"] = m_medicationEdit->toPlainText().trimmed();
    }
    if (!m_sleepInfoEdit->toPlainText().trimmed().isEmpty()) {
        optionalData["health:sleep_info"] = m_sleepInfoEdit->toPlainText().trimmed();
    }
    optionalData["health:sleep_hours"] = QString::number(m_sleepHoursSpinBox->value());
    if (!m_stressInfoEdit->toPlainText().trimmed().isEmpty()) {
        optionalData["health:stress"] = m_stressInfoEdit->toPlainText().trimmed();
    }
    optionalData["health:smoker"] = m_smokerYes->isChecked() ? "是" : "否";
    optionalData["health:drinker"] = m_drinkerYes->isChecked() ? "是" : "否";
    optionalData["health:myopia"] = m_myopiaYes->isChecked() ? "是" : "否";
    optionalData["health:physical_health"] = m_physicalHealthCombo->currentText();
    optionalData["health:mental_health"] = m_mentalHealthCombo->currentText();
    optionalData["health:exercise_frequency"] = m_exerciseFrequencyCombo->currentText();
    optionalData["health:height"] = QString::number(m_heightSpinBox->value());
    optionalData["health:weight"] = QString::number(m_weightSpinBox->value());

    // 计算BMI
    double height = m_heightSpinBox->value() / 100.0; // 转换为米
    double weight = m_weightSpinBox->value();
    if (height > 0) {
        double bmi = weight / (height * height);
        optionalData["health:bmi"] = QString::number(bmi, 'f', 1);
    }

    // 个人特质
    optionalData["personality:mbti"] = m_mbtiCombo->currentText();
    optionalData["personality:left_handed"] = m_leftHandedYes->isChecked() ? "是" : "否";
    if (!m_hobbiesEdit->toPlainText().trimmed().isEmpty()) {
        optionalData["personality:hobbies"] = m_hobbiesEdit->toPlainText().trimmed();
    }

    // 社会关系
    optionalData["social_relations:social_media_usage"] = m_socialMediaUsageCombo->currentText();
    optionalData["social_relations:network_size"] = QString::number(m_socialNetworkSizeSpinBox->value());
    optionalData["social_relations:community_involvement"] = m_communityInvolvementCombo->currentText();

    // 文化与价值观
    optionalData["culture_values:religion"] = m_religionCombo->currentText();
    optionalData["culture_values:political_orientation"] = m_politicalOrientationCombo->currentText();
    optionalData["culture_values:language_usage"] = m_languageUsageCombo->currentText();
    optionalData["culture_values:life_satisfaction"] = m_lifeSatisfactionCombo->currentText();
    optionalData["culture_values:social_concern"] = m_socialConcernCombo->currentText();
    optionalData["culture_values:core_values"] = m_coreValuesCombo->currentText();

    return optionalData;
}

void SubjectInfoDialog::onSubmitButtonClicked() {
    // 验证必填信息
    if (m_nameEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "信息不完整", "请填写姓名");
        return;
    }

    // 收集额外信息
    QMap<QString, QString> optionalData = collectOptionalData();

    // 添加被试信息到数据库
    m_dbManager->addSubject(
        m_nameEdit->text().trimmed(),
        m_genderCombo->currentText(),
        m_ageSpinBox->value(),
        optionalData
        );

    // 获取当前被试ID - 直接使用数据库管理器中的方法获取
    int newSubjectId = m_dbManager->getCurrentSubjectId();

    // 发出信号通知信息采集完成
    emit subjectInfoCollected(newSubjectId);

    // 关闭对话框
    accept();
}
